#!/usr/bin/python3
#
# getPkgs.py -- Scan the package directory and generate the packages.json file
#

import os
import json
import re


class Package:
    def __init__(self, name="", version="", info="", dependencies=""):
        self.name = name
        self.version = version
        self.info = info
        self.dependencies = dependencies


def read_hash_file(hash_file_path):
    with open(hash_file_path, "r", encoding="utf-8") as hash_file:
        lines = hash_file.readlines()
        if len(lines) > 1:
            line = lines[1].strip()
            pos = line.rfind(" ")
            if pos != -1 and pos + 1 < len(line):
                return line[pos + 1:]
    return ""


def read_config_file(config_in_file_path):
    dep_regex = re.compile(r"BR2_PACKAGE_\w+")
    info = ""
    dependencies = ""
    info_set = False

    with open(config_in_file_path, "r", encoding="utf-8") as config_in_file:
        for line in config_in_file:
            line = line.strip()
            if (line.startswith("config") or line.startswith("menuconfig")) and not info_set:
                if line.startswith("menuconfig"):
                    info = line[11:]
                else:
                    info = line[7:]
                info_set = True
            else:
                deps = ", ".join(dep_regex.findall(line))
                if deps:
                    if dependencies:
                        dependencies += ", "
                    dependencies += deps

    return info, dependencies


def get_packages():
    packages = []
    package_dir = "./package"
    db_file_path = "tinybpt_db.json"

    try:
        print(f"Scanning directory: {package_dir}")
        for entry in os.scandir(package_dir):
            if not entry.is_dir():
                continue

            pkg = Package()
            dir_name = entry.name
            pkg.name = dir_name

            hash_file_path = os.path.join(entry.path, f"{dir_name}.hash")
            if os.path.exists(hash_file_path):
                print(f"Reading hash file: {hash_file_path}")
                pkg.version = read_hash_file(hash_file_path)
            else:
                print(f"Hash file not found: {hash_file_path}")

            config_in_file_path = os.path.join(entry.path, "Config.in")
            if not os.path.exists(config_in_file_path):
                config_in_file_path = os.path.join(entry.path, "Config.in.host")

            if not os.path.exists(config_in_file_path):
                print(f"Config file not found: {config_in_file_path}")
                continue

            print(f"Reading config file: {config_in_file_path}")
            pkg.info, pkg.dependencies = read_config_file(config_in_file_path)

            packages.append(pkg)
    except Exception as e:
        print(f"Error accessing directory: {e}")

    try:
        with open(db_file_path, "r", encoding="utf-8") as db_file:
            db_data = json.load(db_file)
    except FileNotFoundError:
        print(f"File {db_file_path} not found. Creating a new one.")
        db_data = {}
    except json.JSONDecodeError as e:
        print(f"Error reading JSON file: {e}")
        db_data = {}

    db_data["packages"] = []

    for pkg in packages:
        pkg_json = {
            "name": pkg.name,
            "version": pkg.version,
            "info": pkg.info,
            "dependencies": pkg.dependencies,
            "download_time": "NULL",
        }
        db_data["packages"].append(pkg_json)

    print(f"Writing to JSON file: {db_file_path}")
    with open(db_file_path, "w", encoding="utf-8") as db_file:
        json.dump(db_data, db_file, indent=4)

    print(f"JSON file {db_file_path} updated successfully.")
    return packages


if __name__ == "__main__":
    get_packages()